package com.example.demo.repository;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import com.example.demo.model.Notice;

public interface NoticeRepository extends JpaRepository<Notice, Long>, JpaSpecificationExecutor<Notice> {

	@SuppressWarnings("serial")
	public default Page<Notice> pageCriteria(Notice notice, Pageable pageable) {

		Page<Notice> page = this.findAll(new Specification<Notice>() {
			@Override
			public Predicate toPredicate(Root<Notice> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				if (notice.getnID() != null) {
					list.add(cb.equal(root.<Long> get("nID"), notice.getnID()));
				}
				if (StringUtils.isNotEmpty(notice.getTitle())) {
					list.add(cb.like(root.<String> get("title"), "%" + notice.getTitle() + "%"));
				}
				if (StringUtils.isNotEmpty(notice.getContent())) {
					list.add(cb.like(root.<String> get("content"), "%" + notice.getContent() + "%"));
				}
				cb.desc(root.<Long> get("updateTime"));

				Predicate[] p = new Predicate[list.size()];
				return cb.and(list.toArray(p));
			}

		}, pageable);
		return page;
	}
}
